package com.itboye.ihomebank.homefragment;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;

public class ActivityNear extends BaseOtherActivity {
	PoiSearch mPoiSearch;
	// 百度地图控件
	private MapView bmapview;
	// 百度地图对象
	private BaiduMap bdMap;
	private double latitude;
	private double longitude;
	ImageView close_icon;
	TextView add_shap_title_tv, traffic_map_btn, chaoshi_map_btn, school_btn,
			hospital_btn, fangyuan_btn;

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.close_icon:
			finish();

			break;
		case R.id.traffic_map_btn:
			nearbySearch(10, "公交站");
			break;
		case R.id.chaoshi_map_btn:
			nearbySearch(10, "超市");
			break;
		case R.id.school_btn:
			nearbySearch(10, "学校");
			break;
		case R.id.hospital_btn:
			nearbySearch(10, "医院");
			break;
		case R.id.fangyuan_btn:
			nearbySearch(10, "小区");
			break;
		default:
			break;
		}
	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		SDKInitializer.initialize(getApplicationContext());
		return R.layout.activity_near;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		add_shap_title_tv.setText("房源附近");
		bdMap = bmapview.getMap();
		latitude = getIntent().getDoubleExtra("latitude", 0.000000);
		longitude = getIntent().getDoubleExtra("longitude", 0.000000);
		mPoiSearch = PoiSearch.newInstance();
		mPoiSearch.setOnGetPoiSearchResultListener(poiListener);
		nearbySearch(10, "小区");
	}

	@Override
	protected void onResume() {
		super.onResume();
		bmapview.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		bmapview.onPause();
	}

	@Override
	protected void onDestroy() {
		mPoiSearch.destroy();
		// 退出时销毁定位
		bdMap.setMyLocationEnabled(false);
		bmapview.onDestroy();
		bmapview = null;
		super.onDestroy();
		// 回收bitmip资源
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	private void nearbySearch(int page, String keyWord) {
		PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption();
		nearbySearchOption.location(new LatLng(latitude, longitude));
		nearbySearchOption.keyword(keyWord);
		nearbySearchOption.radius(3000);// 检索半径，单位是米
		nearbySearchOption.pageNum(page);
		nearbySearchOption.pageCapacity(50);
		mPoiSearch.searchNearby(nearbySearchOption);// 发起附近检索请求
	}

	OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener() {
		public void onGetPoiResult(PoiResult poiResult) {
			// 获取POI检索结果
			if (poiResult == null
					|| poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {// 没有找到检索结果
				Toast.makeText(ActivityNear.this, "未找到结果", Toast.LENGTH_LONG)
						.show();
				return;
			}

			if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {// 检索结果正常返回
				bdMap.clear();
				MyPoiOverlay2 poiOverlay = new MyPoiOverlay2(bdMap);
				poiOverlay.setData(poiResult);// 设置POI数据
				bdMap.setOnMarkerClickListener(poiOverlay);
				poiOverlay.addToMap();// 将所有的overlay添加到地图上
				poiOverlay.zoomToSpan();
				//
				int totalPage = poiResult.getTotalPageNum();// 获取总分页数
				Toast.makeText(
						ActivityNear.this,
						"总共查到" + poiResult.getTotalPoiNum() + "个兴趣点, 分为"
								+ totalPage + "页", Toast.LENGTH_SHORT).show();

			}
		}

		public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
			// 获取Place详情页检索结果
			if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
				Toast.makeText(ActivityNear.this, "抱歉，未找到结果",
						Toast.LENGTH_SHORT).show();
			} else {// 正常返回结果的时候，此处可以获得很多相关信息
				Toast.makeText(
						ActivityNear.this,
						poiDetailResult.getName() + ": "
								+ poiDetailResult.getAddress(),
						Toast.LENGTH_LONG).show();
			}
		}
	};

	private void initLocation() {
		// TODO Auto-generated method stub
		// -----------location config ------------
		// System.out.println("lng" + lng + "lat" + lat);
		// locData = new
		// MyLocationData.Builder().accuracy(radius).direction(100)
		// .latitude(lat).longitude(lng).build();
		// // // 此处设置开发者获取到的方向信息，顺时针0-360
		// baiduMap.setMyLocationData(locData); // 设置定位数据
		// LatLng ll = new LatLng(lat, lng);
		// MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 16); //
		// 设置地图中心点以及缩放级别
		// baiduMap.animateMapStatus(u);
		TextView textView = new TextView(MyApplcation.ctx);
		textView.setText("自定义的覆盖物");
		textView.setTextSize(16);
		// 将View转换为BitmapDescriptor
		BitmapDescriptor descriptor = BitmapDescriptorFactory
				.fromBitmap(BitmapFactory.decodeResource(getResources(),
						R.drawable.weizhi));
		// 设置覆盖物属性，位置、标题、图标。。。
		MarkerOptions markerOptions = new MarkerOptions()
				.position(new LatLng(latitude, longitude)).icon(descriptor)
				.title("标题").zIndex(9).draggable(true);
		// 在地图上添加覆盖物
		bmapview.getMap().addOverlay(markerOptions);

	}

	/**
	 * 自定义显示多少个
	 */
	/**
	 * 自定义显示多少个
	 */
	/**
	 * 自定义显示多少个
	 */
	private class MyPoiOverlay2 extends OverlayManager {
		private PoiResult poiResult = null;

		public MyPoiOverlay2(BaiduMap baiduMap) {
			super(baiduMap);
		}

		public void setData(PoiResult poiResult) {
			this.poiResult = poiResult;
		}

		@Override
		public boolean onMarkerClick(Marker marker) {
			if (marker.getExtraInfo() != null) {
				int index = marker.getExtraInfo().getInt("index");
				PoiInfo poi = poiResult.getAllPoi().get(index);

				// 详情搜索
				mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
						.poiUid(poi.uid));
				return true;
			}
			return false;
		}

		@Override
		public List<OverlayOptions> getOverlayOptions() {
			if ((this.poiResult == null)
					|| (this.poiResult.getAllPoi() == null))
				return null;
			ArrayList<OverlayOptions> arrayList = new ArrayList<OverlayOptions>();
			for (int i = 1; i < this.poiResult.getAllPoi().size(); i++) {
				if (this.poiResult.getAllPoi().get(i).location == null)
					continue;
				// 给marker加上标签
				Bundle bundle = new Bundle();
				bundle.putInt("index", i);
				arrayList.add(new MarkerOptions()
						.icon(BitmapDescriptorFactory
								.fromBitmap(setNumToIcon(i))).extraInfo(bundle)
						.position(this.poiResult.getAllPoi().get(i).location));
			}
			return arrayList;
		}

		/**
		 * 往图片添加数字
		 */
		private Bitmap setNumToIcon(int num) {
			BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(
					R.drawable.icon_marka);
			Bitmap bitmap = bd.getBitmap().copy(Bitmap.Config.ARGB_8888, true);
			// Canvas canvas = new Canvas(bitmap);
			//
			// Paint paint = new Paint();
			// paint.setColor(Color.WHITE);
			// paint.setAntiAlias(true);
			// int widthX;
			// int heightY = 0;
			// if (num < 10) {
			// paint.setTextSize(30);
			// widthX = 8;
			// heightY = 6;
			// } else {
			// paint.setTextSize(20);
			// widthX = 10;
			// }
			//
			// canvas.drawText(String.valueOf(num),
			// ((bitmap.getWidth() / 2) - widthX),
			// ((bitmap.getHeight() / 2) + heightY), paint);
			return bitmap;
		}

	}
}
